package com.example.teaknow;

import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.teaknow.Util.DataUtil;
import com.example.teaknow.Util.Weather.GetWeather;
import com.example.teaknow.Util.Weather.MyApplication;
import com.example.teaknow.Util.Weather.Result;
import com.google.android.material.navigation.NavigationView;
import com.google.gson.Gson;

import androidx.core.view.GravityCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
    public static String weather;
    private AppBarConfiguration mAppBarConfiguration;
    private RadioGroup mTabRadioGroup;
    private SparseArray<Fragment> mFragmentSparseArray;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        initView();
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        //显示日期
        Date cDate = new Date();
        String fDate = new SimpleDateFormat("yyyy-MM-dd").format(cDate);
        View headerView = navigationView.getHeaderView(0);
        TextView textView = (TextView)headerView.findViewById(R.id.textView);
        textView.setText(fDate);

        ImageView imageView=(ImageView)headerView.findViewById(R.id.imageView18);
        volleyGet();
        //imageView.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_collection1));
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home,R.id.nav_collection,R.id.nav_history,R.id.nav_version,R.id.nav_search,R.id.nav_feedback)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }
    /*后退键*/
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
    private void initView(){
        mTabRadioGroup = findViewById(R.id.tabs_rg);
        mFragmentSparseArray = new SparseArray<>();
        HeadlineFragment headlineFragment=HeadlineFragment.newInstance("头条","1");
        KnowFragment knowFragment=KnowFragment.newInstance("知道","2");
        ConsultFragment consultFragment= ConsultFragment.newInstance("咨询","3");
        ManageFragment manageFragment=ManageFragment.newInstance("经营","4");
        DataFragment dataFragment=DataFragment.newInstance("数据","5");
        mFragmentSparseArray.append(R.id.headline_tab, headlineFragment);
        mFragmentSparseArray.append(R.id.know_tab, knowFragment);
        mFragmentSparseArray.append(R.id.consult_tab, consultFragment);
        mFragmentSparseArray.append(R.id.manage_tab, manageFragment);
        mFragmentSparseArray.append(R.id.data_tab, dataFragment);
        mTabRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // 具体的fragment切换逻辑可以根据应用调整，例如使用show()/hide()
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        mFragmentSparseArray.get(checkedId)).commit();
            }
        });
        // 默认显示第一个
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,
                mFragmentSparseArray.get(R.id.headline_tab)).commit();
        //爬取数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    DataUtil.getNewsData(MainActivity.this);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    DataUtil.getTeaData("",MainActivity.this);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }



    public void volleyGet() {
        StringBuffer Bufferurl=new StringBuffer();
        Bufferurl.append("http://apis.juhe.cn/simpleWeather/query?city=");
        Bufferurl.append("厦门");
        Bufferurl.append("&key=ba08e0b3f83a1390d3e30b511eda5688");
        String url=Bufferurl.toString();
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                jsonStringParse(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                System.out.println(error);
                System.out.println("false");
            }
        });
        stringRequest.setTag("Get1");
        MyApplication.getHttpQueue().add(stringRequest);
    }

    private void jsonStringParse(String response) {
        NavigationView navigationView = findViewById(R.id.nav_view);
        View headerView = navigationView.getHeaderView(0);
        Gson gson=new Gson();
        Result result=gson.fromJson(response,Result.class);
        String weather=result.getResult().getFuture().get(0).getWid().getDay();
        System.out.println(result.getResult().getFuture().get(0).getWid().getDay());
        ImageView imageView=(ImageView)headerView.findViewById(R.id.imageView18);
        if("00".equals(weather))
            imageView.setImageDrawable(getResources().getDrawable(R.drawable.qingtian));
        else if("01".equals(weather))
            imageView.setImageDrawable(getResources().getDrawable(R.drawable.duoyun));
        else if ("02".equals(weather))
            imageView.setImageDrawable(getResources().getDrawable(R.drawable.yingtian));
        else
            imageView.setImageDrawable(getResources().getDrawable(R.drawable.yutian));
    }
}